package com.itheima.health.service.impl;

import com.itheima.health.common.DateUtil;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.PoiUtil;

import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;

import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 预约ServiceImpl
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private OrderDao orderDao;

    @Override
    /**
     * 查询预约设置人数
     */
  /*     前端接收的数据格式  map
   "data":[
        {
            "date":2,
            "number":900,
            "reservations":0
        },
        {
            "date":3,
            "number":21000,
            "reservations":0
        },
   */
    @Transactional
    public List<Map> listordersetting(Integer year, Integer month) {

        String fisrtDayOfMonth = DateUtil.getFisrtDayOfMonth(year, month);
        String lastDayOfMonth = DateUtil.getLastDayOfMonth(year, month);
        List<OrderSetting> orderSettings = orderSettingDao.selectordersetting(fisrtDayOfMonth, lastDayOfMonth);
        List<Map> mapList = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings) {
            Map map = new HashMap();
            int date = orderSetting.getOrderDate().getDate();
            map.put("date", date);
            map.put("number", orderSetting.getNumber());
            map.put("reservations", orderSetting.getReservations());
            mapList.add(map);
        }
        return mapList;
    }

    @Override
    public void updateorderstting(OrderSetting orderSetting) {
        /**
         * {
         *     "orderDate":"2022-08-02",
         *     "number":"10"
         * }
         */

        //先根据日期查询id
        OrderSetting one = orderSettingDao.getordersetting(orderSetting);
        if (one == null) {
            //新增数据
            orderSettingDao.insertordersetting(orderSetting);
            return;
        }
        //在根据id更新预约人数
        orderSettingDao.updatenumber(orderSetting, one.getId());
    }

    @Override
    @Transactional
    public boolean savebatch(MultipartFile workbook) {
        //校验文件名是否争取 校验文件格式是否真确
        try {
            List<OrderSetting> arrayList = new ArrayList<>();
            List<String[]> strings = PoiUtil.readExcel(workbook);
            for (String[] str : strings) {
                if (str[0].equals("日期") && str[1].equals("可预约数量")) {
                    continue;
                }
                OrderSetting one = new OrderSetting();
                one.setOrderDate(new SimpleDateFormat("yyyy/MM/dd").parse(str[0]));
                one.setNumber(Integer.valueOf(str[1]));
                arrayList.add(one);
            }
            for (OrderSetting orderSetting : arrayList) {
                Date orderDate = orderSetting.getOrderDate();
                //
                Date date = new Date();   //当前时间
                String s = DateUtil.showDateNow(date); //转成 2022-8-1
                Date date1 = DateUtil.stringToDate(s); //转成时间
                if (orderDate.after(date1)) {
                    updateorderstting(orderSetting);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 根据id查询订单
     * @param id
     * @return
     */
    @Override
    public Order findById(Integer id) {
        Order order = orderDao.selectById(id);
        return order;
    }

    /**
     * 新增预约订单
     * @param order
     * @return
     */
    @Override
    @Transactional
    public Order add(Order order) {
        //判断是否有这一天的预约时间表，判断预约人数是否已经满了，判断是否预约过，一个人不能在同一天重复预约同一项检查
        log.info("预约信息：{}",order);
        //查询是否有该预约时间项，根据时间查询
        OrderSetting orderSetting = orderSettingDao.selectByOrderDate(order.getOrderDate());
        //判断是否有
        if(orderSetting==null){
            //不存在，提示
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        }
        //判断当天预约人数是否满了
        int remainNumber = orderSetting.getNumber() - orderSetting.getReservations();
        //预约剩余人数小于1，预约已满
        if(remainNumber<1){
            throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
        }
        //判断是否已经预约过了
        //根据会员id、预约时间、套餐id查询订单表查询数量
        Long count=orderDao.selectByMemberIdAndDateAndSetmealId(order.getMemberId(),order.getOrderDate(),order.getSetmealId());
        if(count>0){
            //说明该用户在同一天预约过该套餐了
            throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
        }
        //说明可以预约，插入订单
        orderDao.insert(order);
        //已预约人数加1，根据id更新已预约人数
        orderSettingDao.updateReservationsById(orderSetting.getId(),orderSetting.getReservations()+1);
        //返回订单，根据id查询
        return orderDao.selectById(order.getId());
    }


}
